package cn.ibizlab.businesscentral.centralapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.humanresource.domain.Employee;
import cn.ibizlab.businesscentral.core.humanresource.service.IEmployeeService;
import cn.ibizlab.businesscentral.core.humanresource.filter.EmployeeSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"员工" })
@RestController("CentralApi-employee")
@RequestMapping("")
public class EmployeeResource {

    @Autowired
    public IEmployeeService employeeService;

    @Autowired
    @Lazy
    public EmployeeMapping employeeMapping;

    @PreAuthorize("hasPermission(this.employeeMapping.toDomain(#employeedto),'iBizBusinessCentral-Employee-Create')")
    @ApiOperation(value = "新建员工", tags = {"员工" },  notes = "新建员工")
	@RequestMapping(method = RequestMethod.POST, value = "/employees")
    public ResponseEntity<EmployeeDTO> create(@RequestBody EmployeeDTO employeedto) {
        Employee domain = employeeMapping.toDomain(employeedto);
		employeeService.create(domain);
        EmployeeDTO dto = employeeMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.employeeMapping.toDomain(#employeedtos),'iBizBusinessCentral-Employee-Create')")
    @ApiOperation(value = "批量新建员工", tags = {"员工" },  notes = "批量新建员工")
	@RequestMapping(method = RequestMethod.POST, value = "/employees/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<EmployeeDTO> employeedtos) {
        employeeService.createBatch(employeeMapping.toDomain(employeedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "employee" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.employeeService.get(#employee_id),'iBizBusinessCentral-Employee-Update')")
    @ApiOperation(value = "更新员工", tags = {"员工" },  notes = "更新员工")
	@RequestMapping(method = RequestMethod.PUT, value = "/employees/{employee_id}")
    public ResponseEntity<EmployeeDTO> update(@PathVariable("employee_id") String employee_id, @RequestBody EmployeeDTO employeedto) {
		Employee domain  = employeeMapping.toDomain(employeedto);
        domain .setEmployeeid(employee_id);
		employeeService.update(domain );
		EmployeeDTO dto = employeeMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.employeeService.getEmployeeByEntities(this.employeeMapping.toDomain(#employeedtos)),'iBizBusinessCentral-Employee-Update')")
    @ApiOperation(value = "批量更新员工", tags = {"员工" },  notes = "批量更新员工")
	@RequestMapping(method = RequestMethod.PUT, value = "/employees/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<EmployeeDTO> employeedtos) {
        employeeService.updateBatch(employeeMapping.toDomain(employeedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.employeeService.get(#employee_id),'iBizBusinessCentral-Employee-Remove')")
    @ApiOperation(value = "删除员工", tags = {"员工" },  notes = "删除员工")
	@RequestMapping(method = RequestMethod.DELETE, value = "/employees/{employee_id}")
    public ResponseEntity<Boolean> remove(@PathVariable("employee_id") String employee_id) {
         return ResponseEntity.status(HttpStatus.OK).body(employeeService.remove(employee_id));
    }

    @PreAuthorize("hasPermission(this.employeeService.getEmployeeByIds(#ids),'iBizBusinessCentral-Employee-Remove')")
    @ApiOperation(value = "批量删除员工", tags = {"员工" },  notes = "批量删除员工")
	@RequestMapping(method = RequestMethod.DELETE, value = "/employees/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        employeeService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.employeeMapping.toDomain(returnObject.body),'iBizBusinessCentral-Employee-Get')")
    @ApiOperation(value = "获取员工", tags = {"员工" },  notes = "获取员工")
	@RequestMapping(method = RequestMethod.GET, value = "/employees/{employee_id}")
    public ResponseEntity<EmployeeDTO> get(@PathVariable("employee_id") String employee_id) {
        Employee domain = employeeService.get(employee_id);
        EmployeeDTO dto = employeeMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取员工草稿", tags = {"员工" },  notes = "获取员工草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/employees/getdraft")
    public ResponseEntity<EmployeeDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(employeeMapping.toDto(employeeService.getDraft(new Employee())));
    }

    @ApiOperation(value = "检查员工", tags = {"员工" },  notes = "检查员工")
	@RequestMapping(method = RequestMethod.POST, value = "/employees/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody EmployeeDTO employeedto) {
        return  ResponseEntity.status(HttpStatus.OK).body(employeeService.checkKey(employeeMapping.toDomain(employeedto)));
    }

    @PreAuthorize("hasPermission(this.employeeMapping.toDomain(#employeedto),'iBizBusinessCentral-Employee-Save')")
    @ApiOperation(value = "保存员工", tags = {"员工" },  notes = "保存员工")
	@RequestMapping(method = RequestMethod.POST, value = "/employees/save")
    public ResponseEntity<Boolean> save(@RequestBody EmployeeDTO employeedto) {
        return ResponseEntity.status(HttpStatus.OK).body(employeeService.save(employeeMapping.toDomain(employeedto)));
    }

    @PreAuthorize("hasPermission(this.employeeMapping.toDomain(#employeedtos),'iBizBusinessCentral-Employee-Save')")
    @ApiOperation(value = "批量保存员工", tags = {"员工" },  notes = "批量保存员工")
	@RequestMapping(method = RequestMethod.POST, value = "/employees/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<EmployeeDTO> employeedtos) {
        employeeService.saveBatch(employeeMapping.toDomain(employeedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Employee-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Employee-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"员工" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/employees/fetchdefault")
	public ResponseEntity<List<EmployeeDTO>> fetchDefault(EmployeeSearchContext context) {
        Page<Employee> domains = employeeService.searchDefault(context) ;
        List<EmployeeDTO> list = employeeMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Employee-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Employee-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"员工" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/employees/searchdefault")
	public ResponseEntity<Page<EmployeeDTO>> searchDefault(@RequestBody EmployeeSearchContext context) {
        Page<Employee> domains = employeeService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(employeeMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

